package com.youaishujuhui.devops.web.util;

import com.gzyouai.hummingbird.common2.util.StringUtil;
import com.youaishujuhui.devops.web.AppContext;
import com.youaishujuhui.devops.web.domain.manage.SysUser;
import com.youaishujuhui.devops.web.exception.CustomException;
import com.youaishujuhui.devops.web.exception.ExceptionType;
import com.youaishujuhui.devops.web.service.PropertiesService;
import com.youaishujuhui.devops.web.vo.Result;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.io.IOException;

public class WebUtil {
	
	public static ModelAndView response(HttpServletRequest request,HttpServletResponse response, Exception ex) {
		Logger log = LoggerFactory.getLogger(WebUtil.class);
		
		String message=ExceptionType.SYS_FAIL.getMsg();
		int code = ExceptionType.SYS_FAIL.getCode();
		ExceptionType exceptionType = ExceptionType.SYS_FAIL;
		Object exceptionData = null;
		
		if(ex instanceof CustomException){  
        	CustomException customException=(CustomException)ex;  
        	exceptionType = customException.getType();
        	message = exceptionType.getMsg();
        	code = exceptionType.getCode();
			exceptionData = customException.getExceptionData();
        }
		
		if(isAjax(request)){//ajax的跳转交由 js处理
        	ServletOutputStream outputStream = null;
        	try {
	        	Result<String> result = new Result<String>();
	        	result.setCode(code);
	        	result.setMsg(message);
	        	response.reset();
	        	response.setContentType("application/json;charset=UTF-8"); 
	        	outputStream = response.getOutputStream();
	        	outputStream.write(com.alibaba.fastjson.JSONObject.toJSONString(result).getBytes("UTF-8"));  
	            //response.flushBuffer();  
	        } catch (IOException e) {
	        	log.error(e.getMessage());
	        }finally{
	        	if(outputStream!=null){
	        		try {
						outputStream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
	        	}
	        }  
        	return null;
        }else{
        	//登陆异常直接跳到登陆
        	//否则跳到错误页
        	 if(exceptionType.equals(ExceptionType.LOGIN_FAIL)){
        	 	//获取到来源地址
        		 ModelAndView modelAndView = new ModelAndView();  

				 PropertiesService propertiesService = AppContext.applicationContext.getBean("propertiesService",PropertiesService.class);
				 
				 if (propertiesService.getPassportLoginEnable()) {
				 	String path = propertiesService.getPassportLoginUrl();
				 	if(exceptionData != null && !"".equals(exceptionData.toString())){
						String referer = exceptionData.toString();
						path = path + "&backUrl=" + referer;
					}
				 	modelAndView.setViewName("redirect:" + path);
				 } else {
					 modelAndView.setViewName("redirect:/login");
				 }

                 return modelAndView;  
        	 }
        	 
             ModelAndView modelAndView=new ModelAndView();  
             modelAndView.addObject("msg",ex.getMessage());  
             modelAndView.setViewName("error/500");  
             return modelAndView;  
        }
	}  
	
	public static SysUser getLoginUser(HttpServletRequest request){
		Object loginUser = request.getSession().getAttribute(Common.SESSION_LOGIN_USER_KEY);
		return loginUser == null ? null : (SysUser) loginUser;
	}
	
	public static void setLoginUser(HttpServletRequest request, SysUser sysUser){
		if(sysUser != null){
			request.getSession().setAttribute(Common.SESSION_LOGIN_USER_KEY, sysUser);
		}
	}
	
	public static void removeLoginUser(HttpServletRequest request){
		HttpSession session = request.getSession();
		session.removeAttribute(Common.SESSION_LOGIN_USER_KEY);
		session.invalidate();
	}
	
	public static boolean isAjax(HttpServletRequest request){
    	String ajaxHeader = request.getHeader("x-requested-with");
    	
    	return (!StringUtil.isNullOrEmpty(ajaxHeader) 
    			&& ajaxHeader.equals("XMLHttpRequest"));
    }
}
